<?php
namespace App\Module\Admin\Service;

use App\Constants\Constant;
use App\Model\Teacher;
use App\Model\TeacherCredential;
use App\Module\Admin\Request\Teacher\CreateRequest;
use App\Module\Admin\Request\Teacher\UpdateRequest;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Illuminate\Contracts\Hashing\Hasher;

class TeacherService {

    /**
     * @Inject()
     * @var Hasher $hash
     */
    protected $hash;

    public function search($name,$mobile,$pagesize){
        $query = Teacher::query()->latest("teacher_id");

        if(!empty($name)){
            $query->where("name",'like','%'.$name.'%');
        }
        if(!empty($mobile)){
            $query->where("mobile",'like','%'.$mobile.'%');
        }

        return $query->paginate($pagesize);
    }

    public function create(CreateRequest $request){
        return Db::transaction(function() use ($request){
            $teacher = new Teacher();
            $teacher->fill($request->all());
            $teacher->save();

            $credential = new TeacherCredential();
            $credential->setAttribute("teacher_id",$teacher->getAttribute("teacher_id"));
            $credential->setAttribute("username",$request->input("mobile"));
            $credential->setAttribute("type",Constant::USERNAME);
            $credential->setAttribute("content",$this->hash->make($request->input("password")));
            $credential->save();
        });
    }

    public function getById($id){
        return Teacher::query()->find($id);
    }

    public function update(UpdateRequest $request,$id){
        return Db::transaction(function () use($request,$id){
            $model = Teacher::query()->findOrFail($id);
            $model->fill($request->all());
            $model->save();

            $model = TeacherCredential::query()->where([
                ['teacher_id',$model->getAttribute("teacher_id")],
                ['type',Constant::USERNAME]
            ])->firstOrFail();
            $model->setAttribute("username",$request->input("mobile"));
            $model->save();
        });
    }

    public function delete($id){
        return Teacher::destroy($id);
    }

    public function show($id){
        $model = Teacher::query()->findOrFail($id);
        $model->setAttribute("is_show",$model->getAttribute("is_show") % Constant::GLOBAL_TRUE + 1);
        return $model->save();
    }
}